package com.example.demo.controller;

import com.example.demo.dao.UserDao;
import com.example.demo.model.Result;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by admin on 2017/10/13.
 */
@Controller
@RequestMapping(value = "/toutiao")
public class LoginController {
    private static final Logger logger= LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @ResponseBody
    public Result<Object> regis(@RequestParam("username") String username,
                                @RequestParam("password") String password,
                                @RequestParam(value = "remember",defaultValue ="0")int remember,
                                HttpServletResponse response
                               )
    {
        Result<Object> result;
        try{
            Map<String,Object> map=userService.regis(username,password);
            if(map.containsKey("ticket")){
                result=new Result<Object>();
                Cookie cookie=new Cookie("ticket",(String) map.get("ticket"));
                cookie.setPath("/");
                if(remember>0){
                    cookie.setMaxAge(3600*24*5);
                }
                response.addCookie(cookie);

                result.setSuccess(true);
                result.setData("注册成功");
            }else{
                result=new Result<>();
                result.setSuccess(false);
                String message=(String) map.get("msg");
                result.setError(message);
            }
        }catch (Exception e){
            logger.error("注册异常"+e.getMessage());
            e.printStackTrace();
            result=new Result<>(false,"注册异常"+e.getMessage());
        }
        return result;
    }

}
